
//消息服务器地址
var commonMsg="/MessageCenters"

// 后端主项目地址
var commonUrl="https://api.jisupeixun.com";
// 文件服务器地址
var commonFileUrl="https://file.jisupeixun.com";
// 直播服务器地址
var liveUrl="http://localhost:9211"

//转码服务（外网true,）
var transCoding=true;

//域名
var domain =location.host;
var shortdomain = domain.substr(domain.indexOf("."),domain.length);
// 平台名称
var systemTitle = "极速培训2021";

var version=0;
// 公共的方法 弹框、
angular.module('Common', ['toastr', 'restangular'])
.run(function ($rootScope) {
    $rootScope.otherForm = "";
    //是否有转码服务
    $rootScope.transCoding = transCoding;
    //后端的域名
    $rootScope.managerurl=commonUrl;
    //域名
    //如果是ip，不加端口号
    $rootScope.domain = domain;
    $rootScope.shortdomain=shortdomain;
    //系统title
    $rootScope.systemTitle = systemTitle;
    //文件系统
    $rootScope.fileurl = commonFileUrl;
    //上传文件路径    
    $rootScope.upurl = commonUrl;
    //课程静态页面地址
    $rootScope.coursurl = $rootScope.upurl;
    //用户导入文件上传地址 和  访问极速1.0原始地址
    $rootScope.userurl = $rootScope.upurl;
    // 知识库的请求路径
    $rootScope.requestUrl = $rootScope.upurl;
    //题库识别
   $rootScope.questionUrl = "https://tiku.jisupeixun.com/?urls=";
    $rootScope.questionDomain = "https://tiku.jisupeixun.com";
    //系统部署地址··
    $rootScope.DeployUrl = "//" + window.location.host;

})
.config(['toastrConfig', 'RestangularProvider', function (toastrConfig, RestangularProvider) {
    RestangularProvider.setBaseUrl(commonUrl);
    //配置弹窗提示样式
    angular.extend(toastrConfig, {
        autoDismiss: false,     //
        containerId: 'toast-container', // 提示框的ID
        closeButton: true,  // 是否存在管理按扭
        closeHtml: '<button>&times;</button>',  // 关闭html   
        maxOpened: 0,
        newestOnTop: true,
        positionClass: 'toast-top-right',   // 显示位置
        preventDuplicates: false,
        preventOpenDuplicates: false,
        progressBar: true,
        target: 'body'
    });
} ])
// 本地缓存
.factory('LS', [function () {
    return {
        setLS: setLS,
        getLS: getLS,
        delLS: delLS
    }
    // 插入本地缓存
    function setLS(key, value) {
        localStorage.setItem(key, base64encode(escape(JSON.stringify(value))));
        return value;
    }
    //  获取本地缓存
    function getLS(key) {
        var res = localStorage.getItem(key);
        if (res == undefined || res == null || res == "")
            return null;
        return JSON.parse(unescape(base64decode(res)));
    }
    // 删除本地缓存
    function delLS(key) {
        localStorage.removeItem(key);
    }

} ])
//请求知识库 ( 暂时没有用但是也不能删除 有残余)
.factory('AjaxPost', ["sysUserInfo", function (sysUserInfo) {
    return {post:function(url,data){
            var dtd = $.Deferred();
            $.ajax({url:commonUrl+url,
                    type:'post',
                    dataType:'json',
                    beforeSend: function(xhr) {
                        xhr.setRequestHeader("X-Session-Token", sysUserInfo.getuserinfotoken());
                    },
                    headers:{'Content-Type':'application/x-www-form-urlencoded; charset=utf-8;'},
                    data:data
                }).then(function(data){
                    dtd.resolve(data);
                }, function(){
                    //toastr.error("提交失败", "操作失败");
                    dtd.reject();
                });
                return dtd.promise();
        }
    }
} ])
//请求知识库 ( 暂时没有用但是也不能删除 有残余)
.factory('Conne_knowl', ["Restangular", function (Restangular) {
    return Restangular.withConfig(function (RestangularConfigurer) {
    });
} ])
// 请求用户管理 ( 暂时没有用但是也不能删除 有残余)
.factory('Conne_main', ["Restangular", function (Restangular) {
    return Restangular.withConfig(function (RestangularConfigurer) {
    });
} ])

//请求知识库 ( 暂时没有用但是也不能删除 有残余)
.factory('Conne_knowl', ["Restangular", function (Restangular) {
    return Restangular.withConfig(function (RestangularConfigurer) {
    });
} ])
// 请求用户管理 ( 暂时没有用但是也不能删除 有残余)
.factory('Conne_main', ["Restangular", function (Restangular) {
    return Restangular.withConfig(function (RestangularConfigurer) {
    });
} ])

// 提示框的公共方法
.factory('Msg', ['toastr', function (toastr) {
    return {
        // title 标题 txt:内容
        error: function (title, txt) { toastr.error(txt, title); },
        success: function (title, txt) { toastr.success(txt, title); },
        info: function (title, txt) { toastr.info(txt, title); },
        warning: function (title, txt) { toastr.warning(txt, title); },
        clear: function (toast) { toastr.clear(toast); }    // 这个目前测试不好用
    }
} ])
// 判断字符是否为空
.factory('Comm', [function () {
    return {
        isNull: function (str) { if (str == null || str == "" || str == undefined) { return true; } return false; }
    }
} ])
// 拼接路由地址
//-1 清除
//0新增
//1修改
//2统计
//3
.factory('updateUrl', ['$rootScope', function ($rootScope) {
    return {
        upUrl: function (obj) {
            if (obj == 0) {
                $rootScope.otherForm = "/Add";
            } else if (obj == -1) {
                $rootScope.otherForm = "";
            } else if (obj == 1) {
                $rootScope.otherForm = "/Edit";
            } else if (obj == 2) {
                $rootScope.otherForm = "/Statistics";
            }
        }
    }
} ])
// 对话框的公共方法
.factory('MsgCon', ['$q', function ($q) {
    function swal_alert(message, options) {
        return swal_confirm(message, angular.extend({
            title: "系统提示",
            text: message,
            type: "warning",
            showCancelButton: false
        }, options));
    }

    // function swal_info(message, options) {
    //     return swal_alert(message, angular.extend({
    //         type: "info"
    //     }, options));
    // }
    function swal_info(title, text, options, btnText, closeText) {
        var defered = $q.defer();
        var options = angular.extend({
            title: title ? title : '提示',
            text: text ? text : '系统提示',
            type: "info",
            showCancelButton: true,
            confirmButtonText: btnText ? btnText : '删除',
            // confirmButtonColor: '#ff6666',
            cancelButtonText: closeText ? closeText : '取消'
        }, options);
        swal(options, function (r) {                //true 确定   false 删除
            defered.resolve(r);
        }, function (e) {
            defered.reject(e);
        });
        return defered.promise;
    }

    function swal_success(message, options) {
        return swal_alert(message, angular.extend({
            type: "success"
        }, options));
    }

    function swal_error(message, options) {
        return swal_alert(message, angular.extend({
            type: "error"
        }, options));
    }

    function swal_confirm(message, options) {
        var defered = $q.defer();
        var options = angular.extend({
            title: "系统提示",
            text: message,
            type: "warning",
            showCancelButton: true
        }, options);
        swal(options, function (r) {
            defered.resolve(r);
        }, function (e) {
            defered.reject(e);
        });
        return defered.promise;
    }

    // 删除 不带图标
    function del_no_icon(title, text, options, btnText, closeText) {
        var defered = $q.defer();
        var options = angular.extend({
            title: title ? title : '提示',
            text: text ? text : '确认删除吗？',
            type: null,
            showCancelButton: true,
            confirmButtonText: btnText ? btnText : '删除',
            confirmButtonColor: '#ff6666',
            cancelButtonText: closeText ? closeText : '取消'
        }, options);
        swal(options, function (r) {                //true 确定   false 删除
            defered.resolve(r);
        }, function (e) {
            defered.reject(e);
        });
        return defered.promise;
    }
    return {
        alert: swal_alert,
        confirm: swal_confirm,
        info: swal_info,
        success: swal_success,
        error: swal_error,
        delnoicon: del_no_icon
    };

} ])
.factory('HashTable', ['$q', function ($q) {


} ])
//用户信息
.factory('sysUserInfo', ['$http', '$location','$rootScope','Restangular', function ($http, $location,$rootScope,Restangular) {

    return {
        getuserinfo: getuserinfo,
        setuserinfo: setuserinfo,
        getuserinfotoken: getuserinfotoken,
        setuserinfotoken: setuserinfotoken,
        getuserinfotokent: getuserinfotokent,
        getorganizationinfo: getorganizationinfo,
        setorganizationinfo: setorganizationinfo,
        clearuserinfo: clearuserinfo,
        setLS: setlocal,
        getLS: getlocal,
        getOrgDetails:getOrgDetails,
        getStuMenuList:getStuMenuList   
    };    
    function getStuMenuList(){
        return [{id:'da057006d133ece9107bc1f3f8c8dc36',url:"home",appurl:"#xuexi",cnname:"首页",enname:"HomePage",index:0,icon:'&#xe642;'},
                    {id:'f1a75ec21133ece9108585b87c611dfa',url:"home.train",appurl:"#renwu",cnname:"培训",enname:"Train",icon:'&#xe62b;',index:1,children:[
                      {id:'409ba2076133ece9109fcde518c38abd',url:"home.train.task",appurl:"#renwu",cnname:"任务",enname:"Task",index:1,icon:'&#xe651;'},
                        {id:'1e92c21a6133ece9109f8b5ffb47a6eb',url:"home.train.publiclist",appurl:"#course",cnname:"公开课",enname:"OpenClass",index:2,icon:'&#xe725;'},
                      
{id:'49845045f133ee17c6dcce729dd64c3d',url:"home.train.questionnaire",appurl:"#questionnaire",cnname:"问卷",enname:"questionnaire",index:5,icon:'&#xe651;'}						
                    ]},
                    {id:'95f5ebd60133ece91085bd025bbf53eb',url:"home.knowledge",appurl:"#ziliao",cnname:"知识库",enname:"KnowledgeBase",index:2,icon:'&#xe6e1;'},
                    {id:'8b8cb44b9133edb0d84d394dc1b7dba6',url:"home.interlocution",appurl:"#ques",cnname:"问答",enname:"interlocution",index:3,icon:'&#xe670;'},
                  ];
    }
    // 获取企业信息
    function getOrgDetails(){
        Restangular.one("/limit").customPOST({name: "My Message"},"getOrgUsedDetails", {userId: getuserinfo().user_ID}).then(function(response) {
            if(response.errorcode == "0"){                                
                $rootScope.globalOperateObj = response.data;                
                //流量是否超过限制
                if($rootScope.globalOperateObj.unlimitedDate==0&&$rootScope.globalOperateObj.maxFlowSize!=-1){
                    if($rootScope.globalOperateObj.usedFlowSize>$rootScope.globalOperateObj.maxFlowSize){
                           $rootScope.globalOperateObj.disalbleLL=true;//超过
                    }else{
                           $rootScope.globalOperateObj.disalbleLL=false;
                    }
                }else{
                     $rootScope.globalOperateObj.disalbleLL=false;
                }
            }else{
                Msg.error("错误","企业信息获取失败！");
            }
        });
    }
    // 设置本地缓存
    function setlocal(key, value) {
        localStorage.setItem(key, base64encode(escape(JSON.stringify(value))));
        return value;
    }
    // 获取本地缓存
    function getlocal(key) {
        var res = localStorage.getItem(key);
        if (res == undefined || res == null || res == "")
            return null;
        return JSON.parse(unescape(base64decode(res)));
    }
    function sendAjax(token, bak) {
        //创建xhr对象 
        var xhr = new XMLHttpRequest();
        //设置xhr请求的超时时间
        xhr.timeout = 0;
        //设置响应返回的数据格式
        xhr.responseType = "";
        xhr.withCredentials = false;
        //创建一个 post 请求，采用异步
        xhr.open('GET', commonUrl + '/ApiUser/token?token=' + token, false);
        //注册相关事件回调处理函数
        xhr.onload = function (e) {
            if (this.status == 200 || this.status == 304) {
                bak(JSON.parse(this.responseText));
            } else {
                window.location.href = loginUrl;
            }
        };
        //发送数据
        xhr.send();
    }
    function getuserinfo() {
        var userinfo = JSON.parse(localStorage.getItem("userinfo"));
        if(userinfo==null||userinfo==""||userinfo==undefined){
            window.location.href = "/login.html";
            return;
        }
        var orgStr = "", roleStr = "", groupStr = "";
        var orgfrist = "", rolefrist = "", groupfrist = "";
        var orgfristname = "", rolefristname = "", groupfristname = "";
        if (userinfo == null || userinfo == "") {
            if ($location.search().a) {
                sendAjax($location.search().a, function (response) {
                    console.log(response);
                    if (response.errorcode == "0") {
                        console.log(response)
                        setuserinfo(response.data);
                        setuserinfotoken(response.errormsg);
                        userinfo = response.data;
                    } else {
                        window.location.href = loginUrl;
                    }
                });
            } else {
                window.location.href = loginUrl;
            }
        } else {
            if (userinfo.powerLV == "3" || userinfo.powerLV == "99") { //负责人  获取对应 组织结构、权限、用户组 ID 字符串
                if (userinfo.userOrgList != undefined && userinfo.userOrgList.length > 0) {
                    //组织结构 ID 字符串
                    for (var i = 0; i < userinfo.userOrgList.length; i++) {
                        if (userinfo.userOrgList[i]["boss"]) {
                            orgStr += userinfo.userOrgList[i]["organization_ID"] + ",";
                        }
                    }
                    //负者人
                    //只取组织架构的第一级
                    var orglist = angular.copy(userinfo.userOrgList);
                    userinfo.userOrgList.forEach(function (data, index) {
                        orglist.forEach(function (data1, index2) {
                            if (data.organization_ID == data1.parentId) {
                                orglist.splice(index2, 1);
                            }
                        });
                    });
                    orglist.forEach(function (data1, index2) {
                        orgfrist += (orgfrist == "" ? "" : ",") + data1.organization_ID;
                        orgfristname += (orgfristname == "" ? "" : ",") + data1.organization_Name;

                    });

                }
                //权限 ID 字符串
                if (userinfo.userRoleList != undefined && userinfo.userRoleList.length > 0) {
                    for (var i = 0; i < userinfo.userRoleList.length; i++) {
                        if (userinfo.userRoleList[i]["boss"]) {
                            roleStr += userinfo.userRoleList[i]["roles_ID"] + ",";
                        }
                    }
                    //负者人
                    //只取角色的第一级
                    var rolelist = angular.copy(userinfo.userRoleList);
                    userinfo.userRoleList.forEach(function (data, index) {
                        rolelist.forEach(function (data1, index2) {
                            if (data.roles_ID == data1.parentId) {
                                rolelist.splice(index2, 1);
                            }
                        });
                    });
                    rolelist.forEach(function (data1, index2) {
                        rolefrist += (rolefrist == "" ? "" : ",") + data1.roles_ID;
                        rolefristname += (rolefristname == "" ? "" : ",") + data1.roles_Name;
                    });
                }
                //用户组 ID 字符串
                if (userinfo.userGroupList != undefined && userinfo.userGroupList.length > 0) {
                    for (var i = 0; i < userinfo.userGroupList.length; i++) {
                        if (userinfo.userGroupList[i]["boss"]) {
                            groupStr += userinfo.userGroupList[i]["userGroup_ID"] + ",";
                        }
                    }
                    //负者人
                    //只取用户组的第一级
                    var grouplist = angular.copy(userinfo.userGroupList);
                    userinfo.userGroupList.forEach(function (data, index) {
                        grouplist.forEach(function (data1, index2) {
                            if (data.userGroup_ID == data1.parentId) {
                                grouplist.splice(index2, 1);
                            }
                        });
                    });
                    grouplist.forEach(function (data1, index2) {
                        groupfrist += (groupfrist == "" ? "" : ",") + data1.userGroup_ID;
                        groupfristname += (groupfristname == "" ? "" : ",") + data1.userGroup_Name;
                    });
                }
            }

            userinfo.orgStr = orgStr;
            userinfo.roleStr = roleStr;
            userinfo.groupStr = groupStr;

            //负者人的 负者的组织架构，角色，用户组 的第一级
            userinfo.orgfrist = orgfrist;
            userinfo.rolefrist = rolefrist;
            userinfo.groupfrist = groupfrist;

            userinfo.orgfristname = orgfristname;
            userinfo.rolefristname = rolefristname;
            userinfo.groupfristname = groupfristname;
        }
        return userinfo;
    }

    function setuserinfo(userinfo) {
        localStorage.setItem("userinfo", JSON.stringify(userinfo));
    }
    // 设置token
    function setuserinfotoken(token) {
        var tokenObj = { token: token, outTime: "" };
        tokenObj.outTime = new Date().getTime();
        localStorage.setItem("userinfo_token", JSON.stringify(tokenObj));
    }
    //获取token
    function getuserinfotoken() {
        var localtoken = JSON.parse(localStorage.getItem("userinfo_token"));
        var exp = 1000 * 60 * 60 * 24; // 过期时间 1 天
        if (localtoken == undefined || localtoken == null || localtoken == "") {
            localtoken = "";
        } else if (!localtoken.hasOwnProperty('outTime') || !localtoken.hasOwnProperty('token')) {
            localtoken = "";
        } else if (localtoken.hasOwnProperty('outTime') && parseInt(new Date().getTime() - exp) > new Date(localtoken.outTime).getTime()) {
            localtoken = "";
        } else if (localtoken.hasOwnProperty('token')&&localtoken.token!=null&&localtoken.token.length>0) {
            localtoken = localtoken.token.toString();
        }
        return localtoken;
    }
    // token时间
    function getuserinfotokent() {
        var localtoken = JSON.parse(localStorage.getItem("userinfo_token"));
        if (localtoken == undefined || localtoken == null || localtoken == "") {
            localtoken = "";
        } else if (!localtoken.hasOwnProperty('outTime') || !localtoken.hasOwnProperty('token')) {
            localtoken = "";
        } else if (localtoken.hasOwnProperty('token')) {
            localtoken = localtoken.token.toString();
        }
        return localtoken;
    }
    //获取企业信息
    function getorganizationinfo() {
        var orginfo =JSON.parse(localStorage.getItem("organizationInfo"));
        if (orginfo == undefined || orginfo == null || orginfo == "")
            orginfo = "";
        return orginfo;
    }
    //设置企业信息
    function setorganizationinfo(orginfo) {
        localStorage.setItem("organizationInfo", JSON.stringify(orginfo));
        return orginfo;
    }
    // 清除用户信息
    function clearuserinfo(url) {
        Restangular.one("/ApiUser").customPOST({name: "My Message"},"exit", { bqx_xid: "exit",userid: getuserinfo().user_ID}).then(function(response) {
                 setuserinfo(null);
                 setuserinfotoken(null);
                 setorganizationinfo("");

                 if(url==undefined||url==null||url.length<=0){
                    window.location.href ="/login.html";
                 }else{
                     window.location.href =url;
                 }
        });
//        $http.post(commonUrl + '/ApiUser/exit', { bqx_xid: "exit",userid:getuserinfo().user_ID }, {
//            headers: { "X-Session-Token": getuserinfotokent() }
//        }).success(function (data, status, headers, config) {
//            console.log(data)
//        });
//        this.setuserinfo(null);
//        this.setuserinfotoken(null);
//        this.setorganizationinfo("");
//        //window.location.href = loginUrl;
    }
} ])

.factory('CheckID', function () {
    function checkID(ID) {
        if (typeof ID !== 'string') return '非法字符串';
        var city = { 11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古", 21: "辽宁", 22: "吉林", 23: "黑龙江 ", 31: "上海", 32: "江苏", 33: "浙江", 34: "安徽", 35: "福建", 36: "江西", 37: "山东", 41: "河南", 42: "湖北 ", 43: "湖南", 44: "广东", 45: "广西", 46: "海南", 50: "重庆", 51: "四川", 52: "贵州", 53: "云南", 54: "西藏 ", 61: "陕西", 62: "甘肃", 63: "青海", 64: "宁夏", 65: "新疆", 71: "台湾", 81: "香港", 82: "澳门", 91: "国外" };
        var birthday = ID.substr(6, 4) + '/' + Number(ID.substr(10, 2)) + '/' + Number(ID.substr(12, 2));
        var d = new Date(birthday);
        var newBirthday = d.getFullYear() + '/' + Number(d.getMonth() + 1) + '/' + Number(d.getDate());
        var currentTime = new Date().getTime();
        var time = d.getTime();
        var arrInt = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
        var arrCh = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
        var sum = 0, i, residue;
        //if(!/^\d{17}(\d|x)$/i.test(ID)) return '非法身份证';
        if (!/^\d{17}(\d|x)$/i.test(ID)) return false;
        //if(city[ID.substr(0,2)] === undefined) return "非法地区";
        if (city[ID.substr(0, 2)] === undefined) return false;
        //if(time >= currentTime || birthday !== newBirthday) return '非法生日';
        if (time >= currentTime || birthday !== newBirthday) return false;
        for (i = 0; i < 17; i++) {
            sum += ID.substr(i, 1) * arrInt[i];
        }
        residue = arrCh[sum % 11];
        //if (residue !== ID.substr(17, 1)) return '非法身份证哦';
        if (residue !== ID.substr(17, 1)) return false;
        //return city[ID.substr(0,2)]+","+birthday+","+(ID.substr(16,1)%2?" 男":"女");
        return true;
    }
    return {
        checkID: checkID
    }
})

//字符串转html
.filter('to_html', ['$sce',
function ($sce) {
    return function (text) {
        return $sce.trustAsHtml(text);
    };
} ])
//替换题库里的img标签
.filter('to_img', ['$sce',
function ($sce) {
    return function (text, width) {
        var newtext = "";
        if (width) {
            var into=false;
            if(text.indexOf("<label class='annex' >")!=-1){
                newtext = text.replace(new RegExp("<label class='annex' >", 'gm'), "<img style='min-width:40px;max-width:500px;' src='")
            }else{
                newtext = text.replace(new RegExp("<label class= annex  >", 'gm'), "<img style='min-width:40px;max-width:500px;' src='")
            }
        } else {
            if(text.indexOf("<label class='annex'  >")!=-1){
				newtext = text.replace(new RegExp("<label class='annex'>  ", 'gm'), "<img width=40 height=30 src='")
             }else if(text.indexOf("<label class='annex'>")!=-1){
				 newtext = text.replace(new RegExp("<label class='annex'>", 'gm'), "<img width=40 height=30 src='");
			 }else if(text.indexOf("<label class='annex' >")!=-1){
				 newtext = text.replace(new RegExp("<label class='annex' >", 'gm'), "<img width=40 height=30 src='");
			 }else{
                newtext = text.replace(new RegExp("<label class= annex  >", 'gm'), "<img width=40 height=30 src='")
             }
        }
        var twotext = newtext.replace(new RegExp("</label>", 'gm'), "'/>")
        return $sce.trustAsHtml(twotext);
    };
} ])
// 获取 YYYY-MM-DD HH:mm:ss 中的  HH:mm
.filter('to_time', ['$sce',
function ($sce) {
    return function (text) {
        if (text != undefined && text != "" && text != null) {
            text = new Date(text.replace(/-/g,"/"));
            var h=text.getHours()+"";
            var m=text.getMinutes()+"";
            h=(h.length==1?'0':'')+h;
            m=(m.length==1?'0':'')+m;
            return h+ ":" + m;
        } else {
            return "";
        }
    };
} ])

// 获取 YYYY-MM-DD HH:mm:ss 中的  YYYY-MM-DD
.filter('to_date', ['$sce',
function ($sce) {
    return function (text) {
        if (text != undefined && text != "" && text != null) {
            text = new Date(text.replace(/-/g,"/"));
            var splitstr = text.getFullYear() + "-" + ((parseInt(text.getMonth()) + 1) < 10 ? "0" + (parseInt(text.getMonth()) + 1) : (parseInt(text.getMonth()) + 1)) + "-" + (text.getDate() < 10 ? "0" + text.getDate() : text.getDate());
            return splitstr;
        } else {
            return "";
        }
    };
} ])
// 钱币换算
.filter('to_decimal', ['$sce',
function ($sce) {
    return function (text) {
        if (text != undefined && text != "" && text != null) {
            //text = text.toFixed(2);
            text = parseInt(text * 100) / 100;
            return text;
        } else {
            return "0.00";
        }
    };
} ])


//表情替换
.filter('to_face', ['$sce',
function ($sce) {
    return function (text) {
        if (text != undefined) {
            var reg = new RegExp("\\[face_\\d+\\]", "g");
            var facelist = text.match(reg);
            if (facelist != null) {
                for (var i = 0; i < facelist.length; i++) {
                    var imgname = facelist[i].replace("[face_", "").replace("]", "");
                    text = text.replace(facelist[i], "<img src=\"/images/face/" + imgname + ".gif\" />");
                }
            }
            return $sce.trustAsHtml(text);
        }
    };
} ])
// 字节转换 
.filter('to_size', ['$sce',
function ($sce) {
    return function (bytes) {
        if (bytes <= 0) {
            return '0 KB';
        }
        if (bytes != undefined) {
            if (bytes === 0) return '0 KB';
            var k = 1024; // or 1000 
            sizes = ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
            i = Math.floor(Math.log(bytes) / Math.log(k));
            if (i > 0) {
                return (bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i];
            } else {
                var num = Math.round(bytes * 100) / 100;
                if (num <= 0) {
                    return '0.01 ' + sizes[0];
                }
                return num + ' ' + sizes[0];
            }
        } else {
            return '0 KB';
        }
    };
} ])
// 分钟 进制 换算
.filter("to_time_size", ['$sce', function ($sce) {
    return function (data) {
        if (data == undefined || data == null || data == "" || data == 0)
            return "0分钟";
        //分钟 时 天 年
        var res = [];
        var index = 0;
        //分钟 时 天 年                    
        var array = [60, 24, 30, 12];
        var unit = ['分钟', '小时', '天', '月', '年'];
        var playFlag = true;    //可以再取值了            
        while (playFlag) {
            var one = data % array[index]; // 本进制
            if (one > 0) {
                res[index] = one;
                data = parseInt(data / array[index])
                if (array.length <= index + 1) {
                    res[index + 1] = data;
                    palyFlag = false;
                    break;
                }
                index++;
            } else {             
                if(index == 0 && data != 0){
                    res[index] = data % array[index]; 
                    res[index+1] = parseInt(data / array[index]);
                }                
                if(data != 0 && index >=1){
                    res[index+1] = parseInt(data / array[index]);
                }
                playFlag = false;
                break;
            }
        }
        var timeStr = "";
        for (var i = res.length; i > 0; i--) {        
            console.log(res[i - 1]);    
            if (i - 1 == 0) {
                if(res[i - 1]){
                    timeStr += res[i - 1].toFixed(2) + unit[i - 1];
                }                
            } else {
                if(res[i - 1]){
                    timeStr += res[i - 1] + unit[i - 1];
                }                
            }

        }
        return timeStr;
    }
} ])
// 分钟 进制 换算
.filter("time_str", ['$sce', function ($sce) {
    return function (data) {
        if (data == undefined || data == null || data == "" || data == 0)
            return " ";
        var timeStr=data.split(" ")[0];
        timeStr=timeStr.replace("-","年");
        timeStr=timeStr.replace("-","月");
        return timeStr+"日";
    }
} ])
//小时 分钟 进制 换算
.filter("to_time_hour", ['$sce', function ($sce) {
    return function (data) {
        if (data == undefined || data == null || data == "" || data == 0)
            return "0分钟";
        var hours = 0;
        var mins = 0;
        timeStr="";
        hours=parseInt(data/60);
        mins=parseInt(data%60);
        if(hours<=0){
            timeStr=parseInt(data)+"分钟";
        }else{
            timeStr=hours+"小时"+mins+"分钟";
        }
        return timeStr;
    }
} ])
.filter('trustAsResourceUrl', ['$sce', function ($sce) {
    return function (val) {
        return $sce.trustAsResourceUrl(val);
    };
} ])
.filter("get_Extension", function () {
    return function (val) {
        if (val != null && val != '' && val != undefined)
            val.split('.').pop().toLowerCase();
    }
})
.filter("to_repurl", function () {
    return function (val) {
        if (!(val == null || val == undefined || val == "")) {
            if (val.indexOf('8189/Fast-Trianing-FileCenter') < 0) {
                return val.replace('8189', '8189/Fast-Trianing-FileCenter');
            } else {
                return val;
            }
        }
    }
})
//算一个时间距离现在多长时间了。
.filter("todiff", function () {
    return function (val) {
        if (val == null || val == "" || val == undefined) {
            return 0;
        }
        var d1 = new Date(val);
        var d2 = new Date();
        var months;
        months = (d2.getFullYear() - d1.getFullYear()) * 12;
        months -= d1.getMonth();
        months += d2.getMonth();
        return months <= 0 ? 0 : months;
    }
})
.filter("todiff", function () {
    return function (val) {
        if (val == null || val == "" || val == undefined) {
            return 0;
        }
        var d1 = new Date(val);
        var d2 = new Date();
        var months;
        months = (d2.getFullYear() - d1.getFullYear()) * 12;
        months -= d1.getMonth();
        months += d2.getMonth();
        return months <= 0 ? 0 : months;
    }
})
//  标记初始化焦点。第一次打开或用ng-if标记的页面
.directive('setFocus', function () {
    return function (scope, element) {
        element[0].focus();
    };
})
.directive('stringToNumber', function () {
    return {
        require: 'ngModel',
        link: function (scope, element, attrs, ngModel) {
            ngModel.$parsers.push(function (value) {
                return '' + value;
            });
            ngModel.$formatters.push(function (value) {
                return parseFloat(value);
            });
        }
    };
})
// 禁用 路由外部功能
.directive('noClick', ['$rootScope', 'Msg', 'sysUserInfo', function ($rootScope, Msg, sysUserInfo) {
    return {
        restrict: "A",        
        scope: {                                   
            mnt:"&", // 方法            
        },
        link: function (scope, element, attrs) {
            scope.noUserIds = "3b6d0003-a50d-4d6a-99c3-af9a365851d7";
            var btn_list = [];
            //通过权限，筛选对应路由按钮
            scope.btnlist_find2 = function (menus, perm) {
                //                 console.log(menus);
                if (menus != null) {
                    for (var i = 0; i < menus.length; i++) {
                        var menu_obj = menus[i];
                        if ($rootScope.currentTab == menu_obj.name || $rootScope.btnTab == menu_obj.name) {
                            if (menu_obj.hasOwnProperty("childroute")) {
                                menu_obj.childroute = angular.copy(scope.btnlist_find2(menu_obj.childroute, perm));
                            }
                            if (menu_obj.hasOwnProperty("btnlist")) {
                                if (menu_obj.btnlist != 0) {
                                    btn_list = menu_obj.btnlist;
                                }
                            }
                        }
                    }
                }
            }
            scope.getBtnList = function(){
                //遍历菜单权限
                angular.forEach(angular.copy($rootScope.rootscopeauthority), function (data, index, array) {                 
                    scope.btnlist_find2(data.childroute, "");                 
                });
            }
            //遍历按钮是否有权限
            scope.btnlist_find = function (btn_list, btnName) {
                var btncon = false;
                if (btn_list.length > 0) {
                    for (var i = 0; i < btn_list.length; i++) {
                        if (btnName.toLocaleLowerCase().indexOf(btn_list[i].title.toLocaleLowerCase()) !="-1") {
                            btncon = true;
                        }
                    }
                }
                return btncon;
            }
            element.bind("click", function (e) {                                       
                // 匹配权限
                if(attrs.noClick){
                    scope.getBtnList();                    
                    if(scope.btnlist_find(btn_list,attrs.noClick)){
                        scope.$apply(function(){
                            scope.mnt();                                         
                        });                        
                    }else{
                        Msg.info("提示", "无权操作！");                     
                    }
                }else{
                    // 上面都匹配不上了 属于外界按钮了
                    if (scope.noUserIds == sysUserInfo.getuserinfo().user_ID) {
                        Msg.info("提示", "无权操作！");
                        return;
                     }
                     scope.mnt();                 
                }                                                           
            });
        }
    };
} ]);

